﻿@model MenuModel
@section style {
    <style>
        #menus .am-form { overflow:visible; }
        .act-editor-config { width: 100%; min-height: 300px; position: relative; }
        .ace-editor { position: absolute !important; top: 0; right: 0; bottom: 0; left: 0; }
        .field-list span { margin-right: 10px; }
        .field-list li { padding: 10px; color: #000; }
            .field-list li:nth-child(2n) { background-color: #f3f3f3 }
            .field-list li:hover { background-color: #e6e6e6 }
        .table > thead > tr > th { border-bottom: 2px solid #f4f4f4!important; border-right:0; }
    </style>
}
<div class="am-g page" id="menus" v-cloak>
    <div class="am-u-md-8">
        <i-form ref="form" v-model="submitting" action="@ViewBag.SubmitUrl" class="am-form-h" style="position:relative;padding:1.5rem 0" @@success="handleSuccess" :before-submit="handleSubmitBefore">
            <form-item label="菜单Id" label-for="menus_id">
                <input type="text" name="Id" id="menus_id" v-model="menu.Id" readonly />
            </form-item>
            <form-item label="菜单类型" label-for="menus_type">
                <i-select id="menus_type" name="Type" :searchable="false" :options="menuTypes" :val="menu.Type" :on-change="handleMenuType" style="width:100%"></i-select>
            </form-item>
            <form-item label="上级菜单" label-for="menus_pid">
                <i-select name="ParentId" id="menus_pid" :options="parentMenus" :val="menu.ParentId" v-model="parentMenu" tree style="width:100%"></i-select>
            </form-item>
            <form-item label="菜单名称" label-for="menus_name" required>
                <div class="am-u-md-6" style="padding-right:0;"><input type="text" name="Name" id="menus_name" v-model="menu.Name" placeholder="中文名称..." required /></div>
                <div class="am-u-md-6"><input type="text" name="NameEN" id="menus_name_en" v-model="menu.NameEN" placeholder="英文名称..." /></div>
            </form-item>
            <form-item label="前台菜单名称" label-for="menus_web_name">
                <input type="text" name="WebMenuName" v-model="menu.WebMenuName" id="menus_web_name" />
            </form-item>
            <form-item label="菜单模块" label-for="menus_url">
                <div class="am-u-md-6" style="padding-right:0;">
                    <div class="am-u-sm-10 am-padding-h-0">
                        <i-select ref="module" name="ModuleId" :searchable="false" v-model="selectedModule" :val="moduleValue" :options="modules" :on-change="selectModule" style="width:100%" placeholder="常用模块..."></i-select>
                    </div>
                    <div class="am-u-sm-2">
                        <a onclick='parent.selectMenu({ id: 1100, text: "菜单模块配置", url: "@Model.MenuModeuleUrl", icon: "user" })' class="am-icon-plus-circle" title="添加" style="font-size:2.4rem"></a>
                    </div>
                </div>
                <div class="am-u-md-6">
                    <input type="text" name="Url" id="menus_url" v-model="menu.Url" value="" placeholder="请输入菜单链接地址..." />
                </div>
            </form-item>
            <form-item label="前台地址" label-for="menus_web_url">
                <input type="text" name="WebUrl" v-model="menu.WebUrl" id="menus_web_url" />
            </form-item>
            <form-item label="字段设置" v-if="selectedModule && selectedModule.Fields && selectedModule.Fields.length">
                <div>
                    <div>
                        <div class="am-u-md-6" style="padding-left:0;padding-right:0">
                            <i-select :options="selectedModule.Fields" :val.sync="currentField.Name" :on-change="selectField" placeholder="请选择字段..."></i-select>
                        </div>
                        <div class="am-u-md-6" style="padding-right:0">
                            <i-select :options="fieldTypes" :val.sync="currentField.Type" placeholder="请选择字段类型..."></i-select>
                        </div>
                    </div>
                    <div style="padding-top:10px;clear:left">
                        <div class="am-u-md-6" style="padding-left:0;padding-right:0">
                            <input type="text" placeholder="字段标题" v-model="currentField.Title" />
                        </div>
                        <div class="am-u-md-6" style="padding-right:0">
                            <Checkbox v-model="currentField.Required">是否必填</Checkbox>
                            <Checkbox v-model="currentField.Multiple" v-if="currentField.Type==='Select'">是否多选</Checkbox>
                            <Checkbox v-model="currentField.AutoDownload" v-if="currentField.Type==='Editor'||currentField.Type==='SmallEditor'">下载文章图片</Checkbox>
                        </div>
                    </div>
                    <div style="clear:left"></div>
                    <div style="padding: 10px;background-color: #ececec;border-radius: 8px;margin-top: 5px;" v-if="currentField.Type==='Image'||currentField.Type==='Video'||currentField.Type==='File'">
                        文件大小限制：
                        <input type="number" placeholder="上传大小限制（单位M）" v-model="currentField.MaxLength" style="width:80px;display:inline-block" />(M)，
                        文件最少选择：
                        <input type="number" placeholder="个" v-model="currentField.MinCount" style="width:70px;display:inline-block" />
                        最多可选：
                        <input type="number" placeholder="个" v-model="currentField.MaxCount" style="width:70px;display:inline-block" />
                        <div v-if="currentField.Type==='Image'" style="display:inline-block;padding-top:10px">
                            图片大小限制：<input type="number" v-model="currentField.MaxSize.Width" style="width:70px;display:inline-block" />
                            至
                            <input type="number" v-model="currentField.MaxSize.Height" style="width:70px;display:inline-block" />
                        </div>
                        <div v-if="currentField.Type==='File'" class="am-g am-margin-0" style="padding-top:10px">
                            <span class="am-u-sm-2 am-padding-h-0" style="width:98px">文件格式：</span>
                            <div class="am-u-sm-10 am-padding-right-0" style="float:left;width:486px">
                                <input type="text" v-model="currentField.Format" placeholder="逗号隔开如：png,jpg" />
                            </div>
                        </div>
                    </div>
                    <div style="padding-top:10px;" v-if="currentField.Type==='Select'||currentField.Type==='Tag'||currentField.Type==='TreeSelect'">
                        <div>
                            数据源：
                            <i-select name="DataSourceType" id="menus_config_datasource" :options="dataSourceType" :val.sync="currentField.DataSource.DataType" style="width:100%"></i-select>
                        </div>
                        <textarea v-model="currentField.DataSource.Data" rows="2" style="border-top:0" :placeholder="dataSourcePlaceholder"></textarea>
                    </div>
                    <div style="padding-top:10px;">
                        <div>提示信息：</div>
                        <textarea v-model="currentField.Remark" rows="2"></textarea>
                    </div>
                    <div style="text-align:right;padding-top:10px" v-show="currentField.Name">
                        <button type="button" @@click="newField" class="am-btn am-btn-info" v-show="editingField!==null">新建字段</button>
                        <button type="button" @@click="addField" class="am-btn am-btn-info">{{editingField===null?'添加字段':'更新字段'}}</button>
                    </div>
                </div>
                <table class="am-table am-table-hover" v-show="config.Fields&&config.Fields.length">
                    <thead>
                        <tr>
                            <th>&nbsp;</th>
                            <th>字段</th>
                            <th>标题</th>
                            <th>必选</th>
                            <th>编辑</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in config.Fields" :key="item">
                            <td>{{index+1}}.</td>
                            <td>{{item.Name}}</td>
                            <td v-html="item.Title"></td>
                            <td v-html="item.Required?'<strong>是</strong>':'否'"></td>
                            <td style="text-align:right">
                                <a v-show="index>0" @@click="sortField(item, index, 'up')" class="am-icon-chevron-up" style="color:#808080;margin-right:10px" title="向上移动"></a>
                                <a v-show="index+1<config.Fields.length" @@click="sortField(item, index, 'down')" class="am-icon-chevron-down" style="color:#808080;margin-right:10px" title="向下移动"></a>
                                <a @@click="editField(item)" class="am-icon-edit" style="color:#00b1ff;margin-right:10px" title="编辑"></a>
                                <a @@click="removeField(item)" class="am-icon-remove" style="color:red;" title="删除"></a>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div><a @@click="showConfig=!showConfig">{{showConfig?'隐藏高级配置':'显示高级配置'}}</a></div>
            </form-item>
            <form-item label="参数配置"  v-show="showConfig">
                <div class="act-editor-config">
                    <pre class="ace-editor" id="menus_config"></pre>
                </div>
                <input type="hidden" name="Config" id="menu_config_input" />
            </form-item>
            <form-item label="菜单图标" label-for="menus_icon" required>
                <div class="am-u-md-6 am-padding-right-0"><input type="text" name="Icon" v-model="defaultMenu.Icon" id="menus_icon" required /></div>
                <div class="am-u-md-6" style="padding-top:5px"><i :class="menuIcon" style="margin-right:8px"></i><a href="http://fontawesome.io/icons/" target="_blank" class="pull-right fa-2x">更多图标...</a></div>
            </form-item>
            <form-item label="特殊标记" label-for="menus_tags">
                <i-select name="Flags" id="menus_tags" multiple :val="currentFlags" :options="flags" style="width:100%" placeholder="请选择标识..."></i-select>
            </form-item>
            <div class="am-form-group" style="text-align:center;">
                <a class="am-btn am-btn-default" style="margin-right:20px" onclick="_menu_tree.reset()">重置</a>
                <button type="button" v-if="selectedMenu" class="am-btn am-btn-danger" @@click="delMenu">删除菜单</button>
                <i-button type="submit" skin="success" style="padding:8px 30px" :loading="submitting" v-text="submitButtonText"></i-button>
            </div>
        </i-form>
    </div>
    <div class="am-u-md-4">
        <div class="box box-primary direct-chat direct-chat-primary">
            <div class="box-header with-border">
                <h3 class="box-title">菜单列表</h3>
            </div>
            <div class="box-body" id="menu_tree">
                <Tree ref="tree" :data="menus" @@on-select-change="selectMenu" sortable @@on-sort="sort"></Tree>
            </div>
        </div>
    </div>
</div>
@section script {
    <script src="http://res.7csoft.com/lib/ace/ace.js" charset="utf-8" type="text/javascript"></script>
    <script type="text/javascript">
        var _menu_tree = new Vue({
            el: '#menus',
            data: {
                submitting: false,
                showConfig: false,
                //当前选中的Menu
                selectedMenu: null,
                //当前选中的模块
                selectedModule: null,
                moduleValue: null,
                //当前选中字段
                selectedField: {},
                //当前编辑字段
                editingField: null,
                //当前Flags
                currentFlags: null,
                //菜单类型
                menuTypes: @Html.ToJson(Model.MenuTypes),
                dataSourceType: [
                    { id: 'Enum', text: '枚举' },
                    { id: 'Json', text: 'Json数据' },
                    { id: 'Data', text: '自定义数据源' }
                ],
                fieldTypes: @Html.ToJson(Model.FieldTypes),
                //菜单配置
                config: {},
                parentMenus: [],
                parentMenu: null,
                menus: [],
                modules: @Html.ToJson(Model.Modules.Select(a=>new { id = a.Id, text = a.Name, a.Url, a.Flags, a.Config, a.Model, a.DisableConfig })),
                flags: @Html.ToJson(Model.Flags),
                defaultMenu: { Id: 0, Icon: 'circle-o', Type: 1, ParentId: 0 }
            },
            computed: {
                submitButtonText: function () {
                    if (this.submitting)
                        return '正在提交表单...';
                    return this.selectedMenu === null ? '添加菜单' : '保存菜单更改';
                },
                menuIcon: function () {
                    if (!this.defaultMenu.Icon)
                        return '';
                    
                    if (this.defaultMenu.Icon.startsWith('icon-'))
                        return 'icon ' + this.defaultMenu.Icon;
                    if (this.defaultMenu.Icon.startsWith('ic-'))
                        return 'ic ' + this.defaultMenu.Icon;
                    else if (this.defaultMenu.Icon.startsWith('am-icon'))
                        return this.defaultMenu.Icon;
                    return 'am-icon-' + this.defaultMenu.Icon;
                },
                dataSourcePlaceholder: function () {
                    var field = this.editingField ? this.editingField : this.selectedField; 
                    if (field.DataSource.DataType === 'Enum') {
                        return '请输入枚举名称...';
                    } else if (field.DataSource.DataType === 'Data') {
                        return '继承IDataSource接口的数据源...';
                    }
                    return '请输入Json数据(值id,文本text)...';
                },
                currentField: function () {
                    if (!this.editingField)
                    {
                        return this.selectedField;
                    }
                    return this.editingField;
                },
                menu: function () {
                    let menu = this.selectedMenu || this.defaultMenu;
                    if (this.selectedMenu != null) {
                        this.defaultMenu.Icon = this.selectedMenu.Icon;
                    }
                    if (this.selectedMenu === null && this.selectedModule != null)
                    {
                        menu.Url = this.selectedModule.Url;
                        menu.Config = this.selectedModule.Config;
                    }
                    if (this.selectedMenu != null && this.selectedMenu.Flags && this.selectedMenu.Flags.length) {
                        this.currentFlags = this.selectedMenu.Flags.join(',');
                    } else {
                        this.currentFlags = null;
                    }
                    return menu;
                }
            },
            methods: {
                handleMenuType: function (sort) {
                    this.load(sort.id);
                },
                reset: function () {
                    this.config = {};
                    this.defaultMenu = { Id: 0, Icon: 'circle-o', Type: 1, ParentId: (this.lastParentId || 0) };
                    this.selectedMenu = null;
                    this.moduleValue = null;
                    this.selectedModule = null;
                    //this.$refs.module.reset();
                    this.selectedField = {};
                    this.editingField = null;
                },
                updateConfig: function () {
                    let json = "";
                    if (this.config.Fields) {
                        json = JSON.stringify(this.config, null, 4);
                    }
                    this.editor.setValue(json);
                },
                selectField: function (field) {
                    let data = { Name: field.id, Title: field.text, Type: field.type }
                    if (field.type === 'Image' || field.type === 'Video' || field.type === 'File') {
                        data.MaxLength = 2;
                        if (field.type === 'Image') {
                            data.MaxSize = { Width: 300, Height: 300 };
                        }
                    } else if (field.type === 'Select' || field.type === 'Tag') {
                        data.DataSource = { DataType: 'Enum', Data: '' };
                        if (field.Title == '文章标识') {
                            data.DataSource.Data = 'ArticleFlag';
                            data.Multiple = true;
                        }
                    }
                    this.selectedField = data;
                },
                selectModule: function (module) {
                    if (module && module.Model && !module.DisableConfig) {
                        let self = this;
                        if (this.selectedMenu != null)
                            this.selectedMenu.Url = module.Url;
                        $.post('@Model.GetFieldsUrl', { model: module.Model }, function (result) {
                            if (result.succ) {
                                self.$set(self.selectedModule, 'Fields', result.data);
                                if (this.selectedMenu === null) {
                                    if (module.Config) {
                                        self.config = JSON.parse(module.Config);
                                    } else {
                                        self.config = {};
                                    }
                                    self.updateConfig();
                                }
                            } else {
                                alert(result.data);
                            }
                        });
                    }
                },
                newField: function () {
                    this.editingField = null;
                },
                addField: function () {
                    if (this.editingField !== null) {
                        this.editingField = null;
                    } else {
                        if (!this.config.Fields) {
                            this.$set(this.config, "Fields", []);
                        }
                        for (var i = 0; i < this.config.Fields.length; i++) {
                            var field = this.config.Fields[i];
                            if (field.Name === this.currentField.Name) {
                                this.$Message.warning('该字段已添加过，不能重复添加！');
                                return;
                            }
                        }
                        var newField = JSON.parse(JSON.stringify(this.currentField));
                        this.config.Fields.push(newField);
                    }
                    this.updateConfig();
                },
                editField: function (item) {
                    if (!item.DataSource)
                        item.DataSource = { DataType: 'Enum', Data: '' };
                    this.editingField = item;
                },
                removeField: function (item) {
                    this.config.Fields.remove(item);
                    this.updateConfig();
                },
                sortField: function (item, index, sort) {
                    if (sort === 'up')
                        index--;
                    else
                        index++;
                    this.config.Fields.remove(item);
                    this.config.Fields.insertAt(index, item);
                    this.updateConfig();
                },
                delMenu() {
                    if (!confirm("确定删除当前选中的菜单？")) return;
                    var self = this;
                    $.post('@Model.DelUrl', { id: this.selectedMenu.Id }, function (result) {
                        if (result.succ) {
                            self.$Message.success("删除成功！");
                            self.reset();
                            self.load();
                        } else {
                            alert(result.data);
                        }
                    });
                },
                selectMenu(menus) {
                    let menu = menus[0];
                    var self = this;
                    $.post('@Model.InfoUrl', { id: menu.id }, function (data) {
                        if (data.Config) {
                            self.config = data.Config;
                        } else {
                            self.config = {};
                        }
                        self.updateConfig();
                        if (self.selectedMenu === null || self.selectedMenu.Url != data.Url) {
                            let datas = self.$refs.module.datas;
                            let exists = false;
                            datas.forEach(item => {
                                if (item.Url === data.Url) {
                                    exists = true;
                                    //self.selectedModule = item;
                                    self.moduleValue = item.id;
                                }
                            });
                            if (!exists)
                                self.moduleValue = '';
                        } else {
                            console.log("Same Url!!!");
                        }
                        self.selectedMenu = data;
                    });
                },
                sort(menus) {
                    let self = this;
                    $.post('@Model.OrderUrl', {ids: menus}, function (result) {
                        if (result.succ)
                            self.$Message.success('排序成功！');
                        else
                            alert(result.data);
                    });
                },
                load: function (type) {
                    var self = this;
                    if (this.lastMenuType === undefined)
                        this.lastMenuType = 1;
                    if (type === undefined)
                        type = this.lastMenuType;
                    this.lastMenuType = type;
                    $.post('@Model.MenuTreeUrl', { open: true, type: type }, function (data) {
                        self.parentMenus = JSON.parse(JSON.stringify(data));
                        self.menus = data;
                    });
                },
                handleSuccess: function (result) {
                    this.reset();
                    this.$Message.success("保存成功");
                    this.load();
                },
                handleSubmitBefore: function () {
                    if (this.parentMenu != null)
                        this.lastParentId = this.parentMenu.id;
                    var json = this.editor.getValue();
                    if (json)
                        json = JSON.stringify(JSON.parse(json));
                    $('#menu_config_input').val(json);
                    return true;
                }
            },
            mounted: function () {
                var self = this;
                this.load();
                //初始化ace editor
                var editor = ace.edit('menus_config');
                editor.setShowPrintMargin(false);
                //editor.setTheme("ace/theme/twilight");
                editor.session.setMode("ace/mode/json");
                editor.session.on('change', function (e) {
                    console.log("editor changed!");
                    //var json = editor.getValue();
                    //if (json)
                    //    json = JSON.stringify(JSON.parse(json));
                    //$('#menu_config_input').val(json);
                });
                this.editor = editor;
            }
        });
    </script>
}